<!-- 教师时间安排列表页面 -->
<template>
    <div class="teacher-schedule">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>我的课程安排</span>
                    <div>
                        <el-button type="primary" @click="showCreateDialog">创建课程安排</el-button>
                    </div>
                </div>
            </template>

            

            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="日历视图" name="calendar">
                    <div class="calendar-container">
                        <div class="calendar-header">
                            <el-button-group>
                                <el-button @click="changeMonth(-1)" icon="el-icon-arrow-left">上个月</el-button>
                                <el-button @click="currentDate = new Date()" type="primary">今天</el-button>
                                <el-button @click="changeMonth(1)" icon="el-icon-arrow-right">下个月</el-button>
                            </el-button-group>
                            <span class="calendar-title">{{ currentYear }}年{{ currentMonth + 1 }}月</span>
                        </div>
                        
                        <div class="calendar-view">
                            <div class="calendar-weekday-header">
                                <div v-for="(day, index) in weekDays" :key="index" class="weekday-cell">{{ day }}</div>
                            </div>
                            <div class="calendar-grid">
                                <div 
                                    v-for="(day, index) in calendarDays" 
                                    :key="index" 
                                    class="calendar-day" 
                                    :class="{
                                        'other-month': day.otherMonth,
                                        'today': day.isToday,
                                        'has-events': day.events.length > 0
                                    }"
                                >
                                    <div class="day-number">{{ day.day }}</div>
                                    <div class="day-events">
                                        <div 
                                            v-for="event in day.events.slice(0, 3)" 
                                            :key="event.id"
                                            class="calendar-event"
                                            :class="getStatusClass(event.status)"
                                            @click="showDetail(event)"
                                        >
                                            {{ event.studentName }}: {{ formatTimeOnly(event.startTime) }}-{{ formatTimeOnly(event.endTime) }}
                                        </div>
                                        <div v-if="day.events.length > 3" class="more-events">
                                            还有{{ day.events.length - 3 }}个课程...
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
                
                <el-tab-pane label="全部课程" name="all">
                    <el-table :data="schedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="studentName" label="学生姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="状态">
                            <template #default="scope">
                                <el-tag :type="getStatusType(scope.row.status)">
                                    {{ getStatusText(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                                <el-button 
                                    type="danger" 
                                    size="small" 
                                    @click="deleteSchedule(scope.row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="待确认课程" name="pending">
                    <el-table :data="pendingSchedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="studentName" label="学生姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="创建者">
                            <template #default="scope">
                                {{ scope.row.createdBy === 'TEACHER' ? '我创建的' : '学生创建的' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <!-- 如果是学生创建的课程，教师可以确认和取消 -->
                                <template v-if="scope.row.createdBy === 'STUDENT'">
                                    <el-button 
                                        type="success" 
                                        size="small" 
                                        @click="handleConfirm(scope.row)"
                                    >
                                        确认
                                    </el-button>
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="handleCancel(scope.row)"
                                    >
                                        取消
                                    </el-button>
                                </template>
                                <!-- 如果是教师自己创建的课程，教师只能取消 -->
                                <template v-else>
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="handleCancel(scope.row)"
                                    >
                                        取消
                                    </el-button>
                                </template>
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="已确认课程" name="confirmed">
                    <el-table :data="confirmedSchedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="studentName" label="学生姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="状态">
                            <template #default="scope">
                                <el-tag :type="getStatusType(scope.row.status)">
                                    {{ getStatusText(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                                <el-button 
                                    type="danger" 
                                    size="small" 
                                    @click="deleteSchedule(scope.row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="已取消课程" name="canceled">
                    <el-table :data="canceledSchedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="studentName" label="学生姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="状态">
                            <template #default="scope">
                                <el-tag :type="getStatusType(scope.row.status)">
                                    {{ getStatusText(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                                <el-button 
                                    type="danger" 
                                    size="small" 
                                    @click="deleteSchedule(scope.row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="已完成课程" name="completed">
                    <el-table :data="completedSchedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="studentName" label="学生姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="状态">
                            <template #default="scope">
                                <el-tag :type="getStatusType(scope.row.status)">
                                    {{ getStatusText(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                                <el-button 
                                    type="danger" 
                                    size="small" 
                                    @click="deleteSchedule(scope.row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 创建课程安排对话框 -->
        <el-dialog v-model="createDialogVisible" title="创建课程安排" width="500px">
            <div v-if="availableStudents.length === 0" class="empty-data-tip">
                <el-alert
                    title="您还没有已确认的学生预约"
                    type="warning"
                    description="需要有学生预约您的课程并且您已确认后，才能创建课程安排。"
                    show-icon
                    :closable="false"
                />
            </div>
            <el-form v-else :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="100px">
                <el-form-item label="选择学生" prop="studentId">
                    <el-select v-model="scheduleForm.studentId" placeholder="请选择学生" @change="handleStudentChange">
                        <el-option
                            v-for="student in availableStudents"
                            :key="student.id"
                            :label="student.name"
                            :value="student.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="课程" prop="tutoringId">
                    <el-select v-model="scheduleForm.tutoringId" placeholder="请选择课程" :disabled="!scheduleForm.studentId">
                        <el-option
                            v-for="item in availableTutorings"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                        v-model="scheduleForm.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                    />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="scheduleForm.endTime"
                        type="datetime"
                        placeholder="选择结束时间"
                    />
                </el-form-item>
                <el-form-item label="上课地点" prop="location">
                    <el-input v-model="scheduleForm.location" placeholder="请输入上课地点" />
                </el-form-item>
                <el-form-item label="具体要求" prop="requirements">
                    <el-input
                        v-model="scheduleForm.requirements"
                        type="textarea"
                        placeholder="请输入具体要求"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="createDialogVisible = false">取消</el-button>
                    <el-button v-if="availableStudents.length > 0" type="primary" @click="submitSchedule">提交</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="课程详情" width="600px">
            <div v-if="currentSchedule" class="schedule-detail">
                <div class="detail-item">
                    <span class="label">课程名称：</span>
                    <span>{{ currentSchedule.tutoringTitle }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">学生姓名：</span>
                    <span>{{ currentSchedule.studentName }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课时间：</span>
                    <span>{{ formatDateTime(currentSchedule.startTime) }} - {{ formatDateTime(currentSchedule.endTime) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课地点：</span>
                    <span>{{ currentSchedule.location }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">具体要求：</span>
                    <span>{{ currentSchedule.requirements }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">状态：</span>
                    <el-tag :type="getStatusType(currentSchedule.status)">
                        {{ getStatusText(currentSchedule.status) }}
                    </el-tag>
                </div>
                <div v-if="currentSchedule.feedback" class="detail-item">
                    <span class="label">课程反馈：</span>
                    <span>{{ currentSchedule.feedback }}</span>
                </div>
                <div v-if="currentSchedule.rating" class="detail-item">
                    <span class="label">评分：</span>
                    <el-rate v-model="currentSchedule.rating" disabled />
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tutoringService } from '@/api/tutoring'
import { formatDateTime } from '@/utils/format'

const schedules = ref([])
const availableStudents = ref([])
const availableTutorings = ref([])
const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentSchedule = ref(null)
const scheduleFormRef = ref(null)
const activeTab = ref('all')

const scheduleForm = ref({
    studentId: '',
    tutoringId: '',
    startTime: '',
    endTime: '',
    location: '',
    requirements: ''
})

const scheduleRules = {
    studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
    tutoringId: [{ required: true, message: '请选择课程', trigger: 'change' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    location: [{ required: true, message: '请输入上课地点', trigger: 'blur' }]
}

// 根据状态筛选课程安排
const pendingSchedules = computed(() => {
    return schedules.value.filter(schedule => schedule.status === 0)
})

const confirmedSchedules = computed(() => {
    return schedules.value.filter(schedule => schedule.status === 1)
})

const completedSchedules = computed(() => {
    return schedules.value.filter(schedule => schedule.status === 2)
})

const canceledSchedules = computed(() => {
    return schedules.value.filter(schedule => schedule.status === 3)
})

// 获取教师的时间安排列表
const getTeacherSchedules = async () => {
    try {
        const response = await tutoringService.getTeacherSchedules()
        schedules.value = response.data
    } catch (error) {
        ElMessage.error('获取课程安排失败')
    }
}

// 获取已确认预约的学生列表
const getConfirmedStudents = async () => {
    try {
        const response = await tutoringService.getTeacherBookings()
        console.log('获取到的预约数据:', response.data)
        
        // 只保留已确认的预约
        const confirmedBookings = response.data.filter(booking => booking.status === 1)
        
        // 提取不重复的学生信息
        const studentMap = new Map()
        confirmedBookings.forEach(booking => {
            if (!studentMap.has(booking.studentId)) {
                studentMap.set(booking.studentId, {
                    id: booking.studentId,
                    name: booking.studentName || `学生${booking.studentId}`
                })
            }
        })
        
        availableStudents.value = Array.from(studentMap.values())
        console.log('提取的学生信息:', availableStudents.value)
        
        // 如果没有数据，显示提示信息
        if (availableStudents.value.length === 0) {
            ElMessage({
                message: '您还没有已确认的学生预约，请等待学生预约并确认后再创建课程安排',
                type: 'warning',
                duration: 5000,
                showClose: true
            })
        }
    } catch (error) {
        console.error('获取学生数据失败:', error)
        ElMessage.error('获取可用学生失败')
    }
}

// 获取教师的课程列表
const getTeacherTutorings = async () => {
    try {
        const response = await tutoringService.getTeacherTutoring()
        availableTutorings.value = response.data
    } catch (error) {
        ElMessage.error('获取课程列表失败')
    }
}

// 处理学生选择变化
const handleStudentChange = (studentId) => {
    scheduleForm.value.tutoringId = '' // 清空已选课程
}

// 处理标签页切换
const handleTabClick = (tab) => {
    // 切换标签页时不需要重新加载数据，因为我们使用计算属性来筛选
}

// 获取状态类型
const getStatusType = (status) => {
    const types = {
        0: 'warning',  // 待确认
        1: 'success',  // 已确认
        2: 'info',     // 已完成
        3: 'danger'    // 已取消
    }
    return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const texts = {
        0: '待确认',
        1: '已确认',
        2: '已完成',
        3: '已取消'
    }
    return texts[status] || '未知'
}

// 显示创建对话框
const showCreateDialog = () => {
    scheduleForm.value = {
        studentId: '',
        tutoringId: '',
        startTime: '',
        endTime: '',
        location: '',
        requirements: ''
    }
    getConfirmedStudents()
    getTeacherTutorings()
    createDialogVisible.value = true
}

// 日历视图相关数据和方法
const weekDays = ref(['周日', '周一', '周二', '周三', '周四', '周五', '周六'])
const currentDate = ref(new Date())

// 获取当前年份
const currentYear = computed(() => {
    return currentDate.value.getFullYear()
})

// 获取当前月份（0-11）
const currentMonth = computed(() => {
    return currentDate.value.getMonth()
})

// 切换月份
const changeMonth = (offset) => {
    const newDate = new Date(currentDate.value)
    newDate.setMonth(newDate.getMonth() + offset)
    currentDate.value = newDate
}

// 获取日历网格数据
const calendarDays = computed(() => {
    const year = currentYear.value
    const month = currentMonth.value
    const days = []
    
    // 获取当月第一天
    const firstDayOfMonth = new Date(year, month, 1)
    // 获取当月最后一天
    const lastDayOfMonth = new Date(year, month + 1, 0)
    
    // 计算当月天数
    const daysInMonth = lastDayOfMonth.getDate()
    
    // 获取第一天是周几（0-6，0代表周日）
    const firstDayWeekday = firstDayOfMonth.getDay()
    
    // 填充上个月的天数
    const prevMonthLastDay = new Date(year, month, 0).getDate()
    for (let i = 0; i < firstDayWeekday; i++) {
        const dayNumber = prevMonthLastDay - firstDayWeekday + i + 1
        const date = new Date(year, month - 1, dayNumber)
        days.push({
            date,
            day: dayNumber,
            otherMonth: true,
            isToday: isSameDay(date, new Date()),
            events: getDaySchedules(date)
        })
    }
    
    // 填充当月的天数
    for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month, i)
        days.push({
            date,
            day: i,
            otherMonth: false,
            isToday: isSameDay(date, new Date()),
            events: getDaySchedules(date)
        })
    }
    
    // 填充下个月的天数（确保总数是7的倍数）
    const nextMonthDays = 42 - days.length // 6行x7列 = 42
    for (let i = 1; i <= nextMonthDays; i++) {
        const date = new Date(year, month + 1, i)
        days.push({
            date,
            day: i,
            otherMonth: true,
            isToday: isSameDay(date, new Date()),
            events: getDaySchedules(date)
        })
    }
    
    return days
})

// 判断两个日期是否是同一天
const isSameDay = (date1, date2) => {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate()
}

// 获取指定日期的所有课程安排
const getDaySchedules = (date) => {
    return schedules.value.filter(schedule => {
        // 处理ISO 8601格式的字符串
        let scheduleDate;
        if (typeof schedule.startTime === 'string') {
            // 检查是否包含'T'但不包含时区信息
            if (schedule.startTime.includes('T') && !schedule.startTime.includes('Z') && !schedule.startTime.includes('+')) {
                // 添加'Z'表示这是UTC时间，让浏览器正确转换为本地时间
                scheduleDate = new Date(schedule.startTime + 'Z');
            } else {
                scheduleDate = new Date(schedule.startTime);
            }
        } else {
            scheduleDate = new Date(schedule.startTime);
        }
        
        return isSameDay(scheduleDate, date)
    })
}

// 根据状态获取课程在日历中的样式类
const getStatusClass = (status) => {
    const classes = {
        0: 'status-pending',   // 待确认
        1: 'status-confirmed', // 已确认
        2: 'status-completed', // 已完成
        3: 'status-canceled'   // 已取消
    }
    return classes[status] || ''
}

// 格式化时间（只显示时和分）
const formatTimeOnly = (dateTimeString) => {
    if (!dateTimeString) return ''
    
    // 处理ISO 8601格式的字符串（带T和Z的格式）
    let date;
    
    if (typeof dateTimeString === 'string') {
        // 检查是否包含'T'但不包含时区信息
        if (dateTimeString.includes('T') && !dateTimeString.includes('Z') && !dateTimeString.includes('+')) {
            // 添加'Z'表示这是UTC时间，让浏览器正确转换为本地时间
            date = new Date(dateTimeString + 'Z');
        } else {
            date = new Date(dateTimeString);
        }
    } else {
        date = new Date(dateTimeString);
    }
    
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 在scheduleForm中添加时间冲突检查
const checkTimeConflict = async () => {
    const { startTime, endTime } = scheduleForm.value
    if (!startTime || !endTime) return true
    
    const newStart = new Date(startTime)
    const newEnd = new Date(endTime)
    
    // 检查时间范围是否合理
    if (newEnd <= newStart) {
        ElMessage.error('结束时间必须晚于开始时间')
        return false
    }
    
    try {
        // 使用服务器端时间冲突检查
        const response = await tutoringService.checkTimeConflict({
            startTime: scheduleForm.value.startTime,
            endTime: scheduleForm.value.endTime
        })
        
        console.log('时间冲突检查响应:', response) // 调试输出
        
        if (response.code === 0) {
            // 如果返回false，表示有冲突
            if (response.data === false) {
                // 检查extraData是否存在
                if (response.extraData) {
                    const conflicts = response.extraData
                    if (conflicts.length > 0) {
                        const conflict = conflicts[0]
                        ElMessage.error(`时间冲突：与${conflict.studentName || '其他人'}的课程 ${formatDateTime(conflict.startTime)} - ${formatDateTime(conflict.endTime)} 重叠`)
                    } else {
                        ElMessage.error('检测到时间冲突，请选择其他时间')
                    }
                } else {
                    ElMessage.error('检测到时间冲突，请选择其他时间')
                }
                return false
            }
            return true
        } else {
            ElMessage.error(response.message || '检查时间冲突失败')
            return false
        }
    } catch (error) {
        console.error('检查时间冲突出错:', error)
        ElMessage.error('检查时间冲突失败，请重试')
        return false
    }
}

// 更新提交课程安排函数，加入时间冲突检查
const submitSchedule = async () => {
    if (!scheduleFormRef.value) return
    
    await scheduleFormRef.value.validate(async (valid) => {
        if (valid) {
            // 检查时间冲突
            const noConflict = await checkTimeConflict()
            if (!noConflict) {
                return
            }
            
            try {
                await tutoringService.createTeacherSchedule(scheduleForm.value)
                ElMessage.success('课程安排创建成功，等待学生确认')
                createDialogVisible.value = false
                getTeacherSchedules()
            } catch (error) {
                // 显示更详细的错误信息
                const errorMsg = error.response?.data?.message || 
                                (error.response?.data?.data || '创建失败');
                ElMessage({
                    message: errorMsg,
                    type: 'error',
                    duration: 5000,
                    showClose: true
                });
            }
        }
    })
}

// 显示详情
const showDetail = async (schedule) => {
    try {
        const response = await tutoringService.getScheduleDetail(schedule.id)
        currentSchedule.value = response.data
        
        // 打印反馈内容，用于调试
        if (currentSchedule.value && currentSchedule.value.feedback) {
            console.log('课程反馈内容:', currentSchedule.value.feedback)
            console.log('反馈内容字节长度:', new TextEncoder().encode(currentSchedule.value.feedback).length)
        }
        
        detailDialogVisible.value = true
    } catch (error) {
        ElMessage.error('获取详情失败')
    }
}

// 处理确认课程
const handleConfirm = async (schedule) => {
    try {
        await ElMessageBox.confirm('确认接受该课程安排？', '提示', {
            type: 'warning'
        })
        await tutoringService.updateScheduleStatus(schedule.id, 1)
        ElMessage.success('课程确认成功')
        getTeacherSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('确认课程失败')
        }
    }
}

// 处理取消课程
const handleCancel = async (schedule) => {
    try {
        await ElMessageBox.confirm('确认取消该课程安排？', '提示', {
            type: 'warning'
        })
        await tutoringService.updateScheduleStatus(schedule.id, 3)
        ElMessage.success('课程取消成功')
        getTeacherSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('取消课程失败')
        }
    }
}

// 删除课程安排
const deleteSchedule = async (id) => {
    try {
        await ElMessageBox.confirm('确定要删除这个已完成的课程安排吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await tutoringService.deleteSchedule(id)
        ElMessage.success('删除成功')
        getTeacherSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

onMounted(() => {
    getTeacherSchedules()
})
</script>

<style scoped>
.teacher-schedule {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.schedule-detail {
    padding: 20px;
}

.detail-item {
    margin-bottom: 15px;
    line-height: 1.5;
}

.detail-item .label {
    font-weight: bold;
    margin-right: 10px;
    color: #666;
}

.empty-data-tip {
    padding: 20px 0;
}

.mt-3 {
    margin-top: 15px;
}

.text-center {
    text-align: center;
}

/* 添加日历视图相关样式 */
.calendar-container {
  margin-top: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-title {
  font-size: 18px;
  font-weight: bold;
}

.calendar-weekday-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: bold;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.weekday-cell {
  padding: 10px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(6, 1fr);
  border-left: 1px solid #e4e7ed;
  border-top: 1px solid #e4e7ed;
}

.calendar-day {
  min-height: 100px;
  border-right: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
  padding: 5px;
  position: relative;
}

.day-number {
  font-weight: bold;
  margin-bottom: 5px;
}

.other-month {
  color: #909399;
  background-color: #f9f9f9;
}

.today {
  background-color: #f0f9eb;
}

.has-events .day-number {
  color: #409EFF;
}

.calendar-event {
  font-size: 12px;
  padding: 3px 5px;
  margin-bottom: 3px;
  border-radius: 3px;
  background-color: #e1f3d8;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-pending {
  background-color: #fdf6ec;
  border-left: 2px solid #e6a23c;
}

.status-confirmed {
  background-color: #e1f3d8;
  border-left: 2px solid #67c23a;
}

.status-completed {
  background-color: #f2f6fc;
  border-left: 2px solid #909399;
}

.status-canceled {
  background-color: #fef0f0;
  border-left: 2px solid #f56c6c;
  text-decoration: line-through;
}

.more-events {
  font-size: 11px;
  color: #909399;
  text-align: center;
}
</style> 